// index.js
const ctlSize=124;
const baseY=25;
const baseX=55;
const sh=wx.getWindowInfo().screenHeight;
const sw=wx.getWindowInfo().screenWidth;
const centerL={
  x:baseX+ctlSize/2,
  y:baseY+ctlSize/2
}
const centerR={
  x:sh-(baseX+ctlSize/2),
  y:baseY+ctlSize/2
}

function pointInsideCircle(point, circle, r) {  
  if (r===0) return false  
  var dx = circle[0] - point[0]  
  var dy = circle[1] - point[1]  
  return dx * dx + dy * dy <= r * r  
}
function _setPos(sx,sy,cb,center){
  //计算实际位置
  function calRealPos(radius,x,y){
    let a,b,aa,bb,rr;
    a=x-center.x;
    b=y-center.y;
    aa=Math.pow(a,2)
    bb=Math.pow(b,2)
    rr=Math.pow(radius,2)
    console.debug(aa,bb,rr,aa+bb-rr)
    if(!pointInsideCircle([x,y],[center.x,center.y],radius))
    {
      console.debug("not in")
      let thelta = Math.atan(b/a);
      return {
        x:center.x+Math.cos(thelta)*radius*(a>0?1:-1)-baseX,
        y:center.y+Math.sin(thelta)*radius*(a>0?1:-1)-baseY
      }
    }
    else
      return {x:x-baseX,y:y-baseY}
  }
  let {x,y} = calRealPos(ctlSize/2,sx,sy);
  //设置位置
  cb(x,y);
  return {x,y}
}

function posChanged(e,context){
  let id = e.currentTarget.id;
  let screenX=(e.changedTouches[0].clientX);
  let screenY=(e.changedTouches[0].clientY);
  let cb;
  let x,y;
  let dot;
  if(id=='left-ctl'){
    cb = (x,y)=>{
      context.setData({left:{offx:x,offy:y}})
    }
    dot = _setPos(screenY,screenX,cb,centerL)
  }else if(id=='right-ctl'){
    cb = (x,y)=>{
      context.setData({right:{offx:x-(sh-baseX*2-ctlSize),offy:y}})
    }
    dot = _setPos(screenY,screenX,cb,centerR)
  }
  dot.x+=baseX
  dot.y+=baseY
  context.setData({
    dot
  })
}

function reset(e,context){
  let id = e.currentTarget.id;
  if(id=='left-ctl'){
    context.setData({
      dot:centerL,
      left:{
        offx:ctlSize/2,
        offy:ctlSize/2
      }
    })
  }else if(id=='right-ctl'){
    context.setData({
      dot:centerR,
      right:{
        offx:ctlSize/2,
        offy:ctlSize/2
      }
    })
  }
  
}

var lastmove = 0;
var theta = 0;
Page({
  data: {
    left:{
      offx:ctlSize/2,
      offy:ctlSize/2
    },
    right:{
      offx:ctlSize/2,
      offy:ctlSize/2
    },
    dot:centerR,
    debug:false
  },
  onLoad(){
  },
  touchStart(e){
    posChanged(e,this)
  },
  touchEnd(e){
    reset(e,this)
    let that = this;
  },
  touchMove(e){
    // if(e.timeStamp-lastmove>20){
      posChanged(e,this)
      // lastmove=e.timeStamp;
    // }
  }
})
